import pygame
from sys import exit
from subprocess import Popen,PIPE
import random
import hashlib
import requests
from aip import AipSpeech
#绘制文字方法
def fillText(text,position,size):
    #设置字体样式和大小
    my_font = pygame.font.Font("font/simhei.ttf",size)
    #渲染文字
    text = my_font.render(text,True,(0,0,0))
    #绘制文字
    canvas.blit(text,position)

publicFlag = True
def changeLan():
    global publicFlag
    if publicFlag:
        publicFlag = False
        print('状态切换为其它译中')
    else:
        publicFlag = True
        print('状态切换为中译其它')

languageType = 1
def language():
    global publicFlag,languageType
    if publicFlag:
        if languageType == 1:
            fillText('中文',(400,80),25)
            fillText('英文',(600,80),25)
        elif languageType == 2:
            fillText('中文',(400,80),25)
            fillText('德文',(600,80),25)
        elif languageType == 3:
            fillText('中文',(400,80),25)
            fillText('法文',(600,80),25)
    else:
        if languageType == 1:
            fillText('英文',(400,80),25)
            fillText('中文',(600,80),25)
        elif languageType == 2:
            fillText('德文',(400,80),25)
            fillText('中文',(600,80),25)
        elif languageType == 3:
            fillText('法文',(400,80),25)
            fillText('中文',(600,80),25)

#初始化pygame
pygame.init()
#设置窗口大小
canvas = pygame.display.set_mode((1050,660))
#设置窗口标题
pygame.display.set_caption('翻译官')
#设置图片路径
path = "images/bg.jpg"
#加载背景图片
bg = pygame.image.load(path)

inputStr = '按下空格键输入需要翻译的内容'
#切割中文字符
def cutText(text,step):
    slices = []
    for i in range(0,len(text),step):
        slices.append(text[i:i + step])
    return slices
#切割其它语言字符
def getStr(text):
    num = 0
    s = ''
    for i in text:
        s += i
        if i.isspace():
            num += 1
            if num % 5 == 0:
                s += '0'
    return s

def beforeTrans(text):
    global publicFlag
    if publicFlag:
        cutResult = cutText(text,14)
    else:
        temp = getStr(text)
        cutResult = temp.split('0')
    posY = 210
    for text in cutResult:
        fillText(text,(130,posY),20)
        posY += 40

#appId:'20210915000944730',key:'fp19vk7_V5KW2GSndfd5'
#设置请求的参数
appId = '20210915000944730'
key = 'fp19vk7_V5KW2GSndfd5'
tFrom = 'en'
tTo = 'zh'
def getResult(text):
    #生成随机数
    salt = random.randint(32768,65536)
    #生成签名
    sign = appId + text + str(salt) + key
    print('加密前：'+sign)
    md5 = hashlib.md5()
    md5.update(sign.encode('utf-8'))
    sign = md5.hexdigest()
    print('加密后：'+sign)
    #url:'http://api.fanyi.baidu.com/api/trans/vip/translate'
    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    global publicFlag
    if publicFlag:
        params={'q':text,'from':tTo,'to':tFrom,'appid':appId,'salt':salt,'sign':sign}
    else:
        params={'q':text,'from':tFrom,'to':tTo,'appid':appId,'salt':salt,'sign':sign}
    response = requests.get(url,params)
    data = response.json()
    print(data)

    return data['trans_result'][0]['dst']
content = ''

def afterTrans(text):
      global publicFlag
      if publicFlag:
            temp = getStr(text)
            cutResult = temp.split('0')
      else:
            cutResult = cutText(text,14)
      posY = 210
      for text in cutResult:
            fillText(text,(520,posY),20)
            posY += 40
#APPID:'24851802'
#API Key:'gmFwxHASuifsG7Kdla5Pjgjl'
#Secret Key:'xFf5ZSCdDwQGmc099UsFh9mBY3GIfy6C'
#请在下方书写你的代码
audioName = 0
def voice():
    appId = '24851802'
    apiKey = 'gmFwxHASuifsG7Kdla5Pjgjl'
    secretKey = 'xFf5ZSCdDwQGmc099UsFh9mBY3GIfy6C'

    client = AipSpeech(appId,apiKey,secretKey)
    print(client)
    result = client.synthesis(content,'zh',1,{'vol': 6,'per':1,'spd':4})
    #请在下方书写你的代码
    global audioName
    mp3name = "voices/audio"+str(audioName%2)+".mp3"

    if not isinstance(result,dict):
        with open(mp3name,'wb') as f:
            f.write(result)
    print('播放内容：',mp3name)
    pygame.mixer.music.load(mp3name)
    pygame.mixer.music.play()
    #请在下方书写你的代码
    audioName += 1


#关闭窗口
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        #判断是否按下键盘事件
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                print('点击了空格按键')
                p = Popen('python enterbox.py',shell=True,stdout=PIPE)
                print(p.stdout.readline())
                with open('message.txt',encoding='utf-8') as f:
                    mg = f.read()
                print('输入内容为：',mg)
                if mg:
                    inputStr = mg
                else:
                    inputStr = '按下空格键输入需要翻译的内容'
            elif event.key == pygame.K_1:
                print('按键1被按下')
                languageType = 1
                tFrom = 'en'
            elif event.key == pygame.K_2:
                print('按键2被按下')
                languageType = 2
                tFrom = 'de'
            elif event.key == pygame.K_3:
                print('按键3被按下')
                languageType = 3
                tFrom = 'fra'
        #判断鼠标点击事件
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouseX,mouseY = event.pos
            if 485 <= mouseX <= 560 and 82 <= mouseY <= 110:
                print('语言切换功能')
                changeLan()
            elif 180 <= mouseX <= 280 and 440 <= mouseY <= 480:
                print('文本框内容清理功能')
                inputStr = '按下空格键输入需要翻译的内容'
            elif 300 <= mouseX <= 405 and 440 <= mouseY <= 480:
                print('翻译功能')
                content = getResult(inputStr)
                print(content)
            elif 608 <= mouseX <= 740 and 440 <= mouseY <= 480:
                print('语音播放功能')
                voice()

    canvas.blit(bg,(0,0))
    language()
    beforeTrans(inputStr)
    afterTrans(content)
    pygame.display.update()

